import Dep from "./dep.js";
export default class Observer {
  constructor(data) {
    this.data = data;
    this.init();
  }
  init() {
    const data = this.data;
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key]);
    });
  }
  defineReactive(data, key, value) {
    const dep = new Dep();
    /** 子属性为对象 **/
    Observer.create(value);
    Object.defineProperty(data, key, {
      enumerable: true,
      configurable: true,
      get() {
        /**添加watcher**/
        if (Dep.target) {
          dep.addSub(Dep.target);
        }
        return value;
      },
      set(newVal) {
        if (newVal === value) return;
        value = newVal;
        /** 赋值后为对象 **/
        Observer.create(value);
        /**通知watcher**/
        dep.notify();
        // console.log('set', key)
      }
    });
  }
  static create(value) {
    if (!value || typeof value !== "object") return;
    new Observer(value);
  }
}
